package com.jwdf.uda.ui.fragment.question;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.CursorLoader;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jwdf.uda.R;
import com.jwdf.uda.app.AppContext;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.bean.UploadImageResponse;
import com.jwdf.uda.bean.UploadListImageResponse;
import com.jwdf.uda.bean.Upload_Picture;
import com.jwdf.uda.databinding.FragmentNewProblemsBinding;
import com.jwdf.uda.event.ImageSelectorEvent;
import com.jwdf.uda.event.NewProblemsEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.AHttpTaskService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.CategoryGetAction;
import com.jwdf.uda.http.action.QuestionAddAction;
import com.jwdf.uda.http.action.UploadImageListsAction;
import com.jwdf.uda.photopicker.PhotoPickerActivity;
import com.jwdf.uda.runtime.PermissionRequest;
import com.jwdf.uda.runtime.RuntimePermission;
import com.jwdf.uda.ui.activity.NewVoteActivity;
import com.jwdf.uda.ui.activity.QuizDetailActivity;
import com.jwdf.uda.ui.adapter.NewVoteDetailAdapter;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.ui.fragment.progress.LongTask;
import com.jwdf.uda.ui.fragment.progress.TaskList;
import com.jwdf.uda.ui.fragment.question.bean.EditDescribe;
import com.jwdf.uda.ui.fragment.question.bean.NewProblems;
import com.jwdf.uda.ui.fragment.question.bean.NewVote;
import com.jwdf.uda.ui.fragment.question.bean.NewVoteList;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ImageProcessing;
import com.jwdf.uda.utils.PromptUtil;
import com.jwdf.uda.view.dialog.AlertDialog;
import com.jwdf.uda.view.dialog.ConfirmDialog;
import com.jwdf.uda.view.prompt.QuestionPrompt;
import com.jwdf.uda.view.recyclerView.FullyLinearLayoutManager;
import com.jwdf.uda.view.tag.OnTagClickListener;
import com.jwdf.uda.view.tag.Tag;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * Created by Administrator on 2016/9/1.
 */
public class NewProblemsFragment extends BaseFragment implements View.OnTouchListener {
    private static final int PICK_PIC = 0;
    private static int screeWidth;
    private static int imageWidth;
    private static int imageHeight;
    public final long UPLOAD_IMAGE_SIZE_LIMIT = 1024 * 1024;//1M
    private FragmentNewProblemsBinding mBinding;
    private PbBean.PbResQuestionCategoryGet mQuestionCategoryGet;
    private NewVoteDetailAdapter mAdapter;
    private NewProblems mNewProblems;
    private int mTag = 10;
    private Handler handler;
    private ConfirmDialog mDraftBoxDialog;
    private ConfirmDialog mDraftDeleteVote;
    private File uploadImageFile = null;
    private int mImageNumber = 9;
    /**
     * 记录屏幕的宽高的两个变量
     */
    private int screeHeight;
    /**
     * 把图片转成为bitmap，并且在富文本中显示的一个类
     */
    private Html.ImageGetter imageGetter = new Html.ImageGetter() {
        @Nullable
        @Override
        public Drawable getDrawable(String source) {
            try {
                Bitmap bitmap = getImage(source);
                return getMyDrawable(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    };

    /**
     * 获得指定大小的bitmap
     *
     * @param bitmap
     * @return
     */
    private static Drawable getMyDrawable(Bitmap bitmap) {
        Drawable drawable = new BitmapDrawable(bitmap);
        float proportion = (float) screeWidth / imageWidth;
        float floatHeight = proportion * imageHeight;
        int intHeight = (int) (floatHeight + 0.5f);
        drawable.setBounds(0, 0, screeWidth, intHeight);
        return drawable;
    }

    @Override
    public void onDestroyView() {
        closeLoadingPage();
        closeProgressDialog();
        super.onDestroyView();
        EventBusUtil.unregisterEvent(this);
    }

    /**
     * 添加图片
     *
     * @param view
     */
    public void onImgAddClick(View view) {
        String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (RuntimePermission.hasPermissions(getContext(), perms)) {
            List<String> list = saveImage();
            mImageNumber = 9 - list.size();
            if (mImageNumber > 0) {
                PhotoPickerActivity.startActivity(getContext(), PICK_PIC, new ArrayList<String>(), mImageNumber);
            } else {
                Toast.makeText(getContext(), "只能选择9张图片", Toast.LENGTH_LONG).show();
            }
        } else {
            showAlertNotice();
        }

    }

    private void showAlertNotice() {
        final AlertDialog alertDialog = new AlertDialog(getContext(), getContext().getString(R.string.permission_denied_msg), new AlertDialog.CallbackListener() {
            @Override
            public void clickYes() {

            }
        });
        alertDialog.show();
    }

    /**
     * 新增投票
     *
     * @param view
     */
    public void onVoteClick(View view) {
        startActivityFromFragment(NewVoteActivity.class);
    }

    /**
     * 编辑投票
     */
    public void onEditorVote(View view) {
        NewVoteList newVoteList = new NewVoteList();
        newVoteList.setNewVoteList(NewProblems.getInstance().getNewVoteList());
        NewVoteActivity.start(getContext(), newVoteList);
    }

    /**
     * 删除投票
     */
    public void onDeleteVote(View view) {
        //        if (mDraftDeleteVote == null) {
        //            mDraftDeleteVote = new ConfirmDialog(getActivity(), "确定要删除投票内容么？\n删除投票，相关的投票结果也会被删除", "取消", "是的，我要删除");
        if (mDraftDeleteVote == null) {
            mDraftDeleteVote = new ConfirmDialog(getActivity(), "确定要删除投票内容么？\n删除投票，相关的投票结果也会被删除", "取消", "是的，我要删除");
            mDraftDeleteVote.setCallbackListener(new ConfirmDialog.CallbackListener() {
                @Override
                public void clickNo() {

                }

                @Override
                public void clickYes() {
                    NewProblems.getInstance().deleteNewVote();
                    mBinding.ivVote.setVisibility(View.VISIBLE);
                    mBinding.llVote.setVisibility(View.GONE);
                }
            });
        }
        mDraftDeleteVote.show();
        //        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_new_problems, container, false);
        mBinding.setNewProblemsFragment(this);
        initViews();
        return mBinding.getRoot();
    }

    private void initViews() {
        checkPermission();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        /** DisplayMetrics获取屏幕信息 */
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        ViewTreeObserver vto = mBinding.editDescribe.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                screeWidth = mBinding.editDescribe.getMeasuredWidth();
                return true;
            }
        });

        screeHeight = displayMetrics.heightPixels;

        mNewProblems = ConfigUtils.getNewProblems(getContext());
        if (mNewProblems != null) {
            mTag = mNewProblems.getTag();
            if (!mNewProblems.getmNick().equals("")) {
                mBinding.etNick.setText(mNewProblems.getmNick());
            }
            if (!mNewProblems.getmDescribe().equals("")) {
                getDraftBoxs(mNewProblems.getmDescribe(), mNewProblems.getImageList());
            }
            try {
                if (mNewProblems.getNewVoteList() != null && mNewProblems.getNewVoteList().size() > 0) {
                    initVote(mNewProblems.getNewVoteList());
                }
            } catch (Exception e) {

            }
        }

        EventBusUtil.registerEvent(this);
        getCategoryGet();
        mBinding.editDescribe.setOnTouchListener(this);
        mBinding.svFeedback.setParent_scrollview(mBinding.svView);

        mBinding.styleTag.setOnTagClickListener(new OnTagClickListener() {
            @Override
            public void onTagClick(Tag tag, int position) {
                mTag = mBinding.styleTag.setOnTagSelected();
                NewProblems.getInstance().setTag(position);
            }
        });

        if (PromptUtil.isShowQuestionPrompt(getActivity())) {
            new QuestionPrompt(getActivity(), mBinding.etNick, mBinding.llDescribe, mBinding.ivNewProblems,mBinding.ivVote).show();
        }
    }

    /**
     * 加载投票信息
     */
    private void initVote(List<NewVote> list) {
        NewProblems.getInstance().setNewVoteList(list);
        mBinding.llVote.setVisibility(View.VISIBLE);
        mBinding.ivVote.setVisibility(View.GONE);
        mAdapter = new NewVoteDetailAdapter(getActivity());
        mBinding.pullLoadMoreRecyclerView.setHasFixedSize(true);
        final FullyLinearLayoutManager manager = new FullyLinearLayoutManager(getContext());
        //        manager.setOrientation(LinearLayout.VERTICAL);
        //        manager.setSmoothScrollbarEnabled(true);
        mBinding.pullLoadMoreRecyclerView.setLayoutManager(manager);
        mBinding.pullLoadMoreRecyclerView.setAdapter(mAdapter);
        mAdapter.setDetailData(list);
    }

    @PermissionRequest(100)
    private void checkPermission() {
        String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (!RuntimePermission.hasPermissions(getContext(), perms)) {
            RuntimePermission.requestPermissions(this, getString(R.string.app_name), 100, perms);
        }
    }

    /**
     * 获取问题分类
     */
    private void getCategoryGet() {
        onNewRequestCall(CategoryGetAction.newInstance(getContext()).request(new AHttpService.IResCallback<PbBean.PbResQuestionCategoryGet>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionCategoryGet> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    doSuccessResponse(response.body());

                }
            }
        }));

    }

    /**
     * 显示问题分类
     *
     * @param body
     */
    private void doSuccessResponse(PbBean.PbResQuestionCategoryGet body) {
        if (body != null) {
            mQuestionCategoryGet = body;
            List<Tag> tags = new LinkedList<>();
            for (int i = 0; i < mQuestionCategoryGet.getCategoryInfoCount(); i++) {
                tags.add(new Tag(mQuestionCategoryGet.getCategoryInfo(i).getCategoryName()));
            }
            Collections.reverse(tags);
            mBinding.styleTag.addTags(tags);
            if (mTag != 10) {
                mBinding.styleTag.setOnTagClick(mTag);
            }
        }
    }


    public void getDraftBoxs(String describe, List<String> imageList) {
        NewProblems.getInstance().deleteEditDescribeList();
        String content = describe;
        Editable eb = mBinding.editDescribe.getEditableText();
        String[] mContent = content.split("￼");

        int startPosition;
        int i = 0;
        /**
         *
         * 获得草稿的图片和文字信息，并把它展示出来
         */
        for (String string : mContent) {
            //LogUtils.d(string);
            EditDescribe editDescribe = new EditDescribe();
            if (!TextUtils.isEmpty(string)) {
                startPosition = mBinding.editDescribe.getSelectionStart();
                eb.insert(startPosition, string);
                editDescribe.setDescribe(0);
                editDescribe.setmName(string);
                NewProblems.getInstance().setEditDescribeList(editDescribe);
            }
            if (i != mContent.length - 1) {
                String mPicPath = imageList.get(i);
                startPosition = mBinding.editDescribe.getSelectionStart();
                eb.insert(startPosition, Html.fromHtml("<img src=" + mPicPath + ">", imageGetter, null));
                editDescribe = new EditDescribe();
                editDescribe.setDescribe(1);
                editDescribe.setmUrl(mPicPath);
                NewProblems.getInstance().setEditDescribeList(editDescribe);
                i++;
            }
        }
    }

    public void getDraftBox(String describe, List<String> imageList) {
        NewProblems.getInstance().deleteEditDescribeList();
        Editable eb = mBinding.editDescribe.getEditableText();
        String content = describe;
        String[] mContent = content.split("\n");

        int startPosition;
        int i = 0;
        /**
         * 获得草稿的图片和文字信息，并把它展示出来
         */
        for (String string : mContent) {
            //LogUtils.d(string);
            EditDescribe editDescribe = new EditDescribe();
            if (string.contains("￼")) {
                /**
                 * 如果是图片
                 * 1,先判断其来自与照相机还是图库
                 * 2，图库用ImageGetter显示出来
                 * 3，照片用ImageGetter1显示出来
                 */
                String mPicPath = imageList.get(i);
                startPosition = mBinding.editDescribe.getSelectionStart();
                if (mPicPath.contains("content")) {
                    eb.insert(startPosition, Html.fromHtml("<img src=" + mPicPath + "><br/>", imageGetter, null));
                    editDescribe.setDescribe(1);
                    editDescribe.setmUrl(mPicPath);
                } else {
                    eb.insert(startPosition, Html.fromHtml("<img src=" + mPicPath + "><br/>", imageGetter, null));
                    editDescribe.setDescribe(1);
                    editDescribe.setmUrl(mPicPath);
                }
                i++;
                /**
                 * 碰到图片下面直接有文字的情况
                 */
                if (!string.equals("￼")) {
                    String contentPic = string.substring(string.indexOf("￼") + 1);
                    startPosition = mBinding.editDescribe.getSelectionStart();
                    eb.insert(startPosition, contentPic);
                    //                    eb.insert(startPosition, string);
                    editDescribe.setDescribe(0);
                    editDescribe.setmName(contentPic);
                }
            } else {
                /**
                 * 展示文字
                 */
                startPosition = mBinding.editDescribe.getSelectionStart();
                eb.insert(startPosition, string + "\n");
                editDescribe.setDescribe(0);
                editDescribe.setmName(string);
            }
            NewProblems.getInstance().setEditDescribeList(editDescribe);
        }
    }

    private String getRealPathFromURI(Uri contentUri) {
        // 从获得的URI 中获得绝对路径
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(getContext(), contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    /**
     * 通过这个方法对图片进行一定程度的压缩
     *
     * @param source
     * @return
     */
    @Nullable
    private Bitmap getImage(String source) {

        try {
            Bitmap bitmap = null;
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            newOpts.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(source), null, newOpts);
            newOpts.inJustDecodeBounds = false;
            imageWidth = newOpts.outWidth;
            imageHeight = newOpts.outHeight;
            // 缩放比,1表示不缩放
            int scale = 1;

            if (newOpts.outWidth > newOpts.outHeight && newOpts.outWidth > screeWidth) {
                scale = newOpts.outWidth / screeWidth;
            } else if (newOpts.outHeight > newOpts.outWidth && newOpts.outHeight > screeHeight) {
                scale = newOpts.outHeight / screeHeight;
            }
            newOpts.inSampleSize = scale * 2;// 设置缩放比例
            bitmap = BitmapFactory.decodeStream(new FileInputStream(source), null, newOpts);
            return bitmap;
        } catch (Exception e) {
            System.out.println("文件不存在");
            return null;
        }
    }

    public void SaveDescribe(String describe, List<String> imageList) {
        NewProblems.getInstance().deleteEditDescribeList();
        String content = describe;
        String[] mContent = content.split("\n");

        int startPosition;
        int i = 0;
        /**
         * 获得草稿的图片和文字信息，并把它展示出来
         */
        for (String string : mContent) {
            //LogUtils.d(string);
            EditDescribe editDescribe = new EditDescribe();
            if (string.contains("￼")) {
                /**
                 * 如果是图片
                 * 1,先判断其来自与照相机还是图库
                 * 2，图库用ImageGetter显示出来
                 * 3，照片用ImageGetter1显示出来
                 */
                startPosition = mBinding.editDescribe.getSelectionStart();
                String mPicPath = imageList.get(i);
                startPosition = mBinding.editDescribe.getSelectionStart();
                if (mPicPath.contains("content")) {
                    editDescribe.setDescribe(1);
                    editDescribe.setmUrl(mPicPath);
                } else {
                    editDescribe.setDescribe(1);
                    editDescribe.setmUrl(mPicPath);
                }
                i++;
                /**
                 * 碰到图片下面直接有文字的情况
                 */
                if (!string.equals("￼")) {
                    NewProblems.getInstance().setEditDescribeList(editDescribe);
                    editDescribe = new EditDescribe();
                    String contentPic = string.substring(string.indexOf("￼") + 1);
                    editDescribe.setDescribe(0);
                    editDescribe.setmName(contentPic);
                }
            } else {
                /**
                 * 展示文字
                 */
                editDescribe.setDescribe(0);
                editDescribe.setmName(string);
            }
            NewProblems.getInstance().setEditDescribeList(editDescribe);
        }
    }


    public void SaveDescribes(String describe, List<String> imageList) {
        NewProblems.getInstance().deleteEditDescribeList();
        String content = describe;
        String[] mContent = content.split("￼");

        int startPosition;
        int i = 0;
        /**
         * 获得草稿的图片和文字信息，并把它展示出来
         */
        for (String string : mContent) {
            //LogUtils.d(string);
            EditDescribe editDescribe = new EditDescribe();
            if (!TextUtils.isEmpty(string)) {
                editDescribe.setDescribe(0);
                editDescribe.setmName(string);
                NewProblems.getInstance().setEditDescribeList(editDescribe);
            }
            if (i != mContent.length - 1) {
                String mPicPath = imageList.get(i);
                editDescribe = new EditDescribe();
                editDescribe.setDescribe(1);
                editDescribe.setmUrl(mPicPath);
                NewProblems.getInstance().setEditDescribeList(editDescribe);
                i++;
            }

//            if (string.contains("￼")) {
//                /**
//                 * 如果是图片
//                 * 1,先判断其来自与照相机还是图库
//                 * 2，图库用ImageGetter显示出来
//                 * 3，照片用ImageGetter1显示出来
//                 */
//                startPosition = mBinding.editDescribe.getSelectionStart();
//
//                startPosition = mBinding.editDescribe.getSelectionStart();
//                if (mPicPath.contains("content")) {
//                    editDescribe.setDescribe(1);
//                    editDescribe.setmUrl(mPicPath);
//                } else {
//                    editDescribe.setDescribe(1);
//                    editDescribe.setmUrl(mPicPath);
//                }
//                i++;
//                /**
//                 * 碰到图片下面直接有文字的情况
//                 */
//                if (!string.equals("￼")) {
//                    NewProblems.getInstance().setEditDescribeList(editDescribe);
//                    editDescribe = new EditDescribe();
//                    String contentPic = string.substring(string.indexOf("￼") + 1);
//                    editDescribe.setDescribe(0);
//                    editDescribe.setmName(contentPic);
//                }
//            } else {
//                /**
//                 * 展示文字
//                 */
//                editDescribe.setDescribe(0);
//                editDescribe.setmName(string);
//            }

        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
        if ((view.getId() == R.id.edit_describe && canVerticalScroll(mBinding.editDescribe))) {
            mBinding.editDescribe.clearFocus();
            view.getParent().requestDisallowInterceptTouchEvent(true);
            if (event.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return false;
    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    public void onEditFocusable(View view) {
        mBinding.editDescribe.requestFocus();
    }

    public void onEventMainThread(NewProblemsEvent event) {
        switch (event.getEvent()) {
            case NewProblemsEvent.EVENT_COMMENT_SAVE:
                if (judgeNewProblems()) {
                    if (mDraftBoxDialog == null) {
                        mDraftBoxDialog = new ConfirmDialog(getActivity(), "退出新增操作，内容是否要保留?", "不保留", "保留");
                        mDraftBoxDialog.setCallbackListener(new ConfirmDialog.CallbackListener() {
                            @Override
                            public void clickNo() {
                                ConfigUtils.removeNewProblems(getContext());
                                getActivity().finish();
                            }

                            @Override
                            public void clickYes() {
                                saveImage();
                                NewProblems.getInstance().emptyContext();
                                NewProblems.getInstance().setmNick(mBinding.etNick.getText().toString());
                                NewProblems.getInstance().setmDescribe(mBinding.editDescribe.getText().toString());
                                NewProblems.getInstance().setTag(mBinding.styleTag.setOnTagSelected());
                                ConfigUtils.setNewProblems(getContext(), NewProblems.getInstance());
                                NewProblems.getInstance().deleteNewProblems();
                                getActivity().finish();
                            }
                        });
                    }
                    mDraftBoxDialog.show();

                } else {
                    getActivity().finish();
                }

                break;
            case NewProblemsEvent.EVENT_COMMENT_PUBLISHED:
                judge();
                //                askForPermission();
                //                String perms[] = {Manifest.permission.SYSTEM_ALERT_WINDOW};
                //                if (RuntimePermission.hasPermissions(getContext(), perms)) {
                //                    if(NewProblems.getInstance().ismIsUpload()){
                //                        showProgressDialog();
                //                saveImage();
                //                NewProblems.getInstance().setmNick(mBinding.etNick.getText().toString());
                //                NewProblems.getInstance().setmDescribe(mBinding.editDescribe.getText().toString());
                //                NewProblems.getInstance().setTag(mBinding.styleTag.setOnTagSelected());
                //                ConfigUtils.setNewProblems(getContext(), NewProblems.getInstance());
                //                        doUploadAImagesAction();
                //                    }else {
                //                        Toast.makeText(getContext(),"上一个任务还没有完成，请等待",Toast.LENGTH_LONG).show();
                //                    }
                //                } else {
                //                    showAlertSuspension();
                //                }
                break;
            case NewProblemsEvent.EVENT_COMMENT_VOTE:
                NewProblems.getInstance().setNewVoteList(event.getNewVoteList());
                initVote(event.getNewVoteList());
                break;
        }
    }

    public void onEvent(ImageSelectorEvent event) {
        if (event.getCode() == 0) {
            switch (event.getType()) {
                case ImageSelectorEvent.EVENT_ADD:
                    for (int i = 0; i < event.getImages().size(); i++) {
                        final String url = event.getImages().get(i);
                        String urls = url.substring(7, url.length());
                        Editable eb = mBinding.editDescribe.getEditableText();
                        // 获得光标所在位置
                        int startPosition = mBinding.editDescribe.getSelectionStart();
                        eb.insert(startPosition, Html.fromHtml("<img src='" + urls + "'/><br/>", imageGetter, null));
                    }
                    break;
            }
        }
    }

    public boolean judgeNewProblems() {
        return mBinding.etNick.getText().toString().length() > 0 || mBinding.styleTag.setOnTagSelected() != 10;
    }

    protected void doUploadAImagesAction() {


        String title = mBinding.etNick.getText().toString();
        if (title.trim().length() < 3) {
            closeProgressDialog();
            Toast.makeText(getContext(), "问题标题不少于3个字", Toast.LENGTH_LONG).show();
            return;
        }
        if (mBinding.styleTag.setOnTagSelected() == 10) {
            closeProgressDialog();
            Toast.makeText(getContext(), "问题分类没选", Toast.LENGTH_LONG).show();
            return;
        }

        String a = title.substring(title.length() - 1, title.length());
        if (!title.substring(title.length() - 1, title.length()).equals("?") && !title.substring(title.length() - 1, title.length()).equals("？")) {
            closeProgressDialog();
            Toast.makeText(getContext(), "问题结尾须添加问号哦！", Toast.LENGTH_LONG).show();
            return;
        }

//        getActivity().finish();

//        new Handler().postDelayed(new Runnable() {
//            public void run() {
        TaskList taskList = new TaskList();
        taskList.setType("问题");
        taskList.setName(title);
        taskList.setmTaskType(0);
        LongTask.getInstance().setListList(taskList);
//                EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_QUESTION_SHOW, taskList));
//                NewProblems.getInstance().setmIsUpload(false);
//        NewProblems.getInstance().setContext(getContext());
//                setIsRequest(false);
        // do something
        SaveDescribes(mBinding.editDescribe.getText().toString(), saveImage());
        doUploadImagesAction();
//            }

//        }, 500);

        //        if(hasImageAToken) {
        //            doHasImageTokenSuccess(list2);
        //        }
    }

    private void doUploadImagesAction() {
        List<EditDescribe> list2 = NewProblems.getInstance().getEditDescribeList();
        List<String> listImage = new ArrayList<>();
        for (int i = 0; i < list2.size(); i++) {
            if (list2.get(i).getDescribe() == 1) {
                listImage.add("file://" + list2.get(i).getmUrl());

            }
        }
        if (listImage.size() == 0) {
            doHasImageTokenSuccess(list2);
        } else {
            ImageCompression(listImage.size(), listImage);
        }
    }

    private void doUploadImageAction(final int plan, final List<File> imageUrl) {
        UploadImageListsAction action = new UploadImageListsAction(AppContext.getInstance(), imageUrl, 0);
        onNewRequestCall(action.request(new UploadImageListsAction.IResCallback<String>() {
            @Override
            public void onCallback(int resultCode, UploadListImageResponse response) {
//                if(getView() != null) {
                if (resultCode != 0) {
//                    EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_QUESTION_ERROR));
//                    setIsRequest(true);
//                    cancelRequest();
//                    NewProblems.getInstance().setmIsUpload(true);
                    saveImage();
//                        NewProblems.getInstance().emptyContext();
                    NewProblems.getInstance().setmNick(mBinding.etNick.getText().toString());
                    NewProblems.getInstance().setmDescribe(mBinding.editDescribe.getText().toString());
                    NewProblems.getInstance().setTag(mBinding.styleTag.setOnTagSelected());
                    ConfigUtils.setNewProblems(AppContext.getInstance(), NewProblems.getInstance());
                    NewProblems.getInstance().deleteNewProblems();
                    return;
                }
                doUploadImageResponse(plan, response);
//                }
            }
        }));
    }

    //    private void doUploadImageResponse(int plan, UploadListImageResponse response) {
    ////        NewProblems.getInstance().getEditDescribeList().get(plan).setToken(response.getToken());
    ////        List<EditDescribe> list2 = NewProblems.getInstance().getEditDescribeList();
    ////
    ////        doHasImageTokenSuccess(list2);
    //    }

    private void doUploadImageResponse(int plan, UploadListImageResponse response) {

        Gson gson = new Gson();
        List<String> list = new ArrayList<>();
        for (int i = 0; i < plan; i++) {
            JsonObject a1 = response.getUpload_picture().getAsJsonObject("upload_picture_" + (i + 1) + "");
            java.lang.reflect.Type type = new TypeToken<Upload_Picture>() {
            }.getType();
            Upload_Picture upload_picture = gson.fromJson(a1, type);
            list.add(upload_picture.getToken());

        }
//        String aa=upload_picture.getToken();
        int j = 0;
        for (int i = 0; i < NewProblems.getInstance().getEditDescribeList().size(); i++) {
            if (NewProblems.getInstance().getEditDescribeList().get(i).getDescribe() == 1) {
                NewProblems.getInstance().getEditDescribeList().get(i).setToken(list.get(j));
                j = j + 1;
            }
        }


        List<EditDescribe> list2 = NewProblems.getInstance().getEditDescribeList();

        doHasImageTokenSuccess(list2);
    }

    private void doUploadImageAction(final int plan, final String imageUrl) {
//        UploadImageAction action = new UploadImageAction(NewProblems.getInstance().getContext(), imageUrl);


    }

    private void doUploadImageResponse(int plan, String imageUrl, UploadImageResponse response) {
        NewProblems.getInstance().getEditDescribeList().get(plan).setToken(response.getToken());
        List<EditDescribe> list2 = NewProblems.getInstance().getEditDescribeList();

        doHasImageTokenSuccess(list2);
    }

    //判断是否图片已经上传完成
    private void doHasImageTokenSuccess(List<EditDescribe> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getDescribe() == 1) {
                if (list.get(i).getToken().equals("")) {
                    return;
                }
            }
        }
        onPublishedQuestion();
    }

    public void onPublishedQuestion() {

        int categoryCode = mQuestionCategoryGet.getCategoryInfo(mBinding.styleTag.setOnTagSelected()).getCategoryCode();
        List<PbBean.PbBaseReqDescription> descriptionList = getDescriptionLIst();
        List<PbBean.PbBaseReqVoteOption> voteOptionList = getVoteOption();
        QuestionAddAction questionAddAction = QuestionAddAction.newInstance(AppContext.getInstance(), mBinding.etNick.getText().toString(), categoryCode, descriptionList, voteOptionList, 0);
        onNewRequestCall(questionAddAction.request(new AHttpTaskService.IResCallback<PbBean.PbResQuestionAddQuestion>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionAddQuestion> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
//                    closeProgressDialog();
                    if (resultCode != 0) {
//                    EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_QUESTION_ERROR));
//                    setIsRequest(true);
//                    cancelRequest();
//                    NewProblems.getInstance().setmIsUpload(true);
                        saveImage();
//                    NewProblems.getInstance().emptyContext();
                        NewProblems.getInstance().setmNick(mBinding.etNick.getText().toString());
                        NewProblems.getInstance().setmDescribe(mBinding.editDescribe.getText().toString());
                        NewProblems.getInstance().setTag(mBinding.styleTag.setOnTagSelected());
                        ConfigUtils.setNewProblems(AppContext.getInstance(), NewProblems.getInstance());
                        NewProblems.getInstance().deleteNewProblems();
                        return;
                    }
                    closeProgressDialog();
                    Toast.makeText(AppContext.getInstance(), "发表成功", Toast.LENGTH_LONG).show();
                    ConfigUtils.removeNewProblems(AppContext.getInstance());
                    NewProblems.getInstance().deleteNewProblems();
                    //                    getActivity().finish();
                    EventBusUtil.post(new NewProblemsEvent(NewProblemsEvent.EVENT_COMMENT_RELEASE));
                    QuizDetailActivity.start(getActivity(),response.body().getQuestionId(),true);
                    getActivity().finish();
//                EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_QUESTION_COMPLETE));
//                setIsRequest(true);
//                cancelRequest();
                }
            }
        }));
    }

    /**
     * 保持图片url
     */
    public List<String> saveImage() {
        Editable eb = mBinding.editDescribe.getEditableText();
        String html = Html.toHtml(eb);
        int startIndex;
        int endIndex;
        List<String> imageList = new ArrayList<>();
        String[] mContentEb = html.split("\n");
        for (String string : mContentEb) {
            if (string.contains("src=")) {
                if (string.contains("jpg")) {
                    startIndex = string.indexOf("src=") + 5;
                    endIndex = string.lastIndexOf("jpg") + 3;
                    String uri = string.substring(startIndex, endIndex);
                    imageList.add(uri);
                } else {
                    final String jpeg = "jpeg";
                    if (string.contains(jpeg)) {
                        startIndex = string.indexOf("src=") + 5;
                        endIndex = string.lastIndexOf(jpeg) + jpeg.length();
                        String uri = string.substring(startIndex, endIndex);
                        imageList.add(uri);
                    } else if (string.contains("png")) {
                        startIndex = string.indexOf("src=") + 5;
                        endIndex = string.lastIndexOf("png") + 3;
                        String uri = string.substring(startIndex, endIndex);
                        imageList.add(uri);
                    }
                }
            }
        }
        NewProblems.getInstance().setImageList(imageList);
        return imageList;
    }

    public List<PbBean.PbBaseReqDescription> getDescriptionLIst() {
        //        parsingDescribe(mBinding.editDescribe.getText().toString());
        List<PbBean.PbBaseReqDescription> descriptionList = new ArrayList<>();
        List<EditDescribe> list2 = NewProblems.getInstance().getEditDescribeList();
        for (int i = 0; i < list2.size(); i++) {
            if (list2.get(i).getDescribe() == 0) {
                PbBean.PbBaseReqDescription.Builder builder = PbBean.PbBaseReqDescription.newBuilder();
                builder.setDescType(PbBean.PbSignBaseDescriptionType.DESCRIPTION_TPYE_TEXT);
                String mName = list2.get(i).getmName();
//                if (list2.get(i).getmName().equals("")) {
//                    mName = "\n";
//                } else {
//                    mName = mName + "\n";
//                }
                builder.setDescription(mName);
                descriptionList.add(builder.build());
            } else {
                PbBean.PbBaseReqDescription.Builder builder = PbBean.PbBaseReqDescription.newBuilder();
                builder.setDescType(PbBean.PbSignBaseDescriptionType.DESCRIPTION_TPYE_IMG);
                builder.setDescription(list2.get(i).getToken());
                descriptionList.add(builder.build());
            }
        }
        return descriptionList;
    }

    public List<PbBean.PbBaseReqVoteOption> getVoteOption() {
        List<PbBean.PbBaseReqVoteOption> voteOptionList = new ArrayList<>();
        if (NewProblems.getInstance().getNewVoteList().size() > 0) {
            if (NewProblems.getInstance().getNewVoteList().get(0).getDescription().length() > 0) {
                PbBean.PbBaseReqVoteOption.Builder builder = PbBean.PbBaseReqVoteOption.newBuilder();
                builder.setDescription(NewProblems.getInstance().getNewVoteList().get(0).getDescription());
                List<String> list = new ArrayList<>();
                for (int i = 0; i < NewProblems.getInstance().getNewVoteList().get(0).getUploadImages().size(); i++) {
                    list.add(NewProblems.getInstance().getNewVoteList().get(0).getUploadImages().get(i).getImageToken());
                }
                builder.addAllOptionImage(list);
                voteOptionList.add(builder.build());
            }

            if (NewProblems.getInstance().getNewVoteList().get(1).getDescription().length() > 0) {
                PbBean.PbBaseReqVoteOption.Builder builder = PbBean.PbBaseReqVoteOption.newBuilder();
                builder.setDescription(NewProblems.getInstance().getNewVoteList().get(1).getDescription());
                List<String> list = new ArrayList<>();
                for (int i = 0; i < NewProblems.getInstance().getNewVoteList().get(1).getUploadImages().size(); i++) {
                    list.add(NewProblems.getInstance().getNewVoteList().get(1).getUploadImages().get(i).getImageToken());
                }
                builder.addAllOptionImage(list);
                voteOptionList.add(builder.build());
            }
            if (NewProblems.getInstance().getNewVoteList().get(2).getDescription().length() > 0) {
                PbBean.PbBaseReqVoteOption.Builder builder = PbBean.PbBaseReqVoteOption.newBuilder();
                builder.setDescription(NewProblems.getInstance().getNewVoteList().get(2).getDescription());
                List<String> list = new ArrayList<>();
                for (int i = 0; i < NewProblems.getInstance().getNewVoteList().get(2).getUploadImages().size(); i++) {
                    list.add(NewProblems.getInstance().getNewVoteList().get(2).getUploadImages().get(i).getImageToken());
                }
                builder.addAllOptionImage(list);
                voteOptionList.add(builder.build());
            }
            if (NewProblems.getInstance().getNewVoteList().get(3).getDescription().length() > 0) {
                PbBean.PbBaseReqVoteOption.Builder builder = PbBean.PbBaseReqVoteOption.newBuilder();
                builder.setDescription(NewProblems.getInstance().getNewVoteList().get(3).getDescription());
                List<String> list = new ArrayList<>();
                for (int i = 0; i < NewProblems.getInstance().getNewVoteList().get(3).getUploadImages().size(); i++) {
                    list.add(NewProblems.getInstance().getNewVoteList().get(3).getUploadImages().get(i).getImageToken());
                }
                builder.addAllOptionImage(list);
                voteOptionList.add(builder.build());
            }
        }
        return voteOptionList;
    }

    private void showAlertSuspension() {
        final AlertDialog alertDialog = new AlertDialog(getContext(), getContext().getString(R.string.permission_denied_msgs), new AlertDialog.CallbackListener() {
            @Override
            public void clickYes() {
                showProgressDialog();
//                saveImage();
//                NewProblems.getInstance().setmNick(mBinding.etNick.getText().toString());
//                NewProblems.getInstance().setmDescribe(mBinding.editDescribe.getText().toString());
//                NewProblems.getInstance().setTag(mBinding.styleTag.setOnTagSelected());
//                ConfigUtils.setNewProblems(getContext(), NewProblems.getInstance());
                doUploadAImagesAction();
            }
        });
        alertDialog.show();
    }


    /**
     * 请求用户给予悬浮窗的权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    public void askForPermission() {
        if (!Settings.canDrawOverlays(getContext())) {

            final AlertDialog alertDialog = new AlertDialog(getContext(), getContext().getString(R.string.permission_denied_msgs), new AlertDialog.CallbackListener() {
                @Override
                public void clickYes() {
                    published();
                }
            });
            alertDialog.show();
        } else {
            published();
        }
    }

    public void judge() {
//        if (Build.VERSION.SDK_INT == 23) {
//            askForPermission();
//        } else {
//            askForPermissions();
//        }
        published();
    }

    public void askForPermissions() {
        String perms[] = {Manifest.permission.SYSTEM_ALERT_WINDOW};
        if (!RuntimePermission.hasPermissions(getContext(), perms)) {
            final AlertDialog alertDialog = new AlertDialog(getContext(), getContext().getString(R.string.permission_denied_msgs), new AlertDialog.CallbackListener() {
                @Override
                public void clickYes() {
                    published();
                }
            });
            alertDialog.show();
        } else {
            published();
        }
    }

    public void published() {
//        if (NewProblems.getInstance().ismIsUpload()) {
        showProgressDialog();
        doUploadAImagesAction();
//        } else {
//            Toast.makeText(getContext(), "上一个任务还没有完成，请等待", Toast.LENGTH_LONG).show();
//        }
    }

    public void ImageCompression(final int pan, final List<String> imageList) {

        List<File> imageFileList = new ArrayList<>(imageList.size());
        for (int i = 0; i < imageList.size(); i++) {
            final int location = i;
            NewProblems.getInstance().addImageFileList(null, location);
            File imageFile = null;
            try {
                imageFile = new File(new URI(imageList.get(i)));
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

            if (imageFile.length() > UPLOAD_IMAGE_SIZE_LIMIT) {
                String imageType = ImageProcessing.getImageType(imageFile.getAbsolutePath());
                final String filePath = imageFile.getAbsolutePath();
                try {
                    uploadImageFile = ImageProcessing.createTempImageFile(imageType);//将要保存图片的路径
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Luban.get(AppContext.getInstance())
                        .load(imageFile)
                        .putGear(Luban.THIRD_GEAR)
                        .setFilename(uploadImageFile.getAbsolutePath())
                        .asObservable()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnError(new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                throwable.printStackTrace();
                            }
                        })
                        .onErrorResumeNext(new Func1<Throwable, Observable<? extends File>>() {
                            @Override
                            public Observable<? extends File> call(Throwable throwable) {
                                return Observable.empty();
                            }
                        })
                        .subscribe(new Action1<File>() {
                            @Override
                            public void call(File file) {
                                // TODO 压缩成功后调用，返回压缩后的图片文件
                                NewProblems.getInstance().getImageFileList().set(location, file);
                                doImageCompressionSuccess(imageList, pan);
                            }
                        });    //启动压缩


            } else {
                NewProblems.getInstance().getImageFileList().set(location, imageFile);
                doImageCompressionSuccess(imageList, pan);
            }
        }
    }


    //判断图片是否压缩完成
    private void doImageCompressionSuccess(List<String> list, final int pan) {
        List<File> fileList = NewProblems.getInstance().getImageFileList();
        if (list.size() == NewProblems.getInstance().getImageFileList().size()) {
            for (int i = 0; i < NewProblems.getInstance().getImageFileList().size(); i++) {
                if (NewProblems.getInstance().getImageFileList().get(i) == null) {
                    return;
                }
            }
        } else {
            return;
        }
        doUploadImageAction(pan, NewProblems.getInstance().getImageFileList());
    }
}
